package cdu.sl.service.impl;

import cdu.sl.common.SecurityConstants;
import cdu.sl.entity.Permission;
import cdu.sl.entity.Role;
import cdu.sl.entity.User;
import cdu.sl.entity.UserRole;
import cdu.sl.mapper.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * Spring Security 数据库认证 从数据库加载用户信息
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {
    private final UserDao userDao;

    private final HttpServletRequest httpServletRequest;

    private final RoleDao roleDao;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("=====> 从数据库加载用户信息：{}", username);

        try {
            User user = userDao.findByUsername(username);
            if (user == null) {
                log.error("用户不存在: {}", username);
                throw new UsernameNotFoundException("用户不存在: " + username);
            }

            log.info("查询到用户详情:{}", user);

            // 分配用户角色
            Set<Role> userRoles = user.getRoles();
            Set<GrantedAuthority> authorities = new HashSet<>();
            
            if (userRoles != null && !userRoles.isEmpty()) {
                for (Role userRole : userRoles) {
                    if (userRole != null && userRole.getName() != null) {
                        String roleName = SecurityConstants.ROLE_PREFIX + userRole.getName();
                        authorities.add(new SimpleGrantedAuthority(roleName));
                        log.info("添加角色: {}", roleName);
                        // 分配用户权限
                        Role role=roleDao.findByName(userRole.getName());
                        Set<Permission> permissions = role.getPermissions();
                        for (Permission permission : permissions) {
                            authorities.add(new SimpleGrantedAuthority(permission.getName()));
                        }
                        log.info("添加权限：{}",permissions);
                    } else {
                        log.warn("发现无效角色数据");
                    }
                }
            } else {
                log.warn("用户 {} 没有分配任何角色", username);
            }

            log.info("用户 {} 认证完成，拥有 {} 个权限", username, authorities.size());

            // 保存用户信息到会话范围
            httpServletRequest.getSession().setAttribute("userInfo",user);
            
            // 构建UserDetails对象
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                    user.getUsername(),
                    user.getPassword(),
                    authorities
            );
            
            log.info("返回UserDetails: username={}, 权限数={}", 
                    userDetails.getUsername(), userDetails.getAuthorities().size());
            
            return userDetails;

        } catch (Exception e) {
            log.error("加载用户信息时发生错误: {}", username, e);
            throw new UsernameNotFoundException("加载用户信息时发生错误: " + e.getMessage(), e);
        }
    }
}
